#!/usr/bin/env python
# -*- coding: utf-8 -*-

import subprocess
import sys
import os

print("Installing project dependencies with conflict resolution...")

# Use --user flag to avoid permission issues
user_flag = ["--user"]

# First, try to install numpy with --no-deps to avoid TBB issues
print("\nStep 1: Installing numpy (without dependencies to avoid TBB conflicts)...")
try:
    subprocess.check_call([sys.executable, "-m", "pip", "install", "numpy==1.21.6", "--no-deps"] + user_flag)
    print("✓ Successfully installed numpy")
except subprocess.CalledProcessError as e:
    print("⚠ Warning: Failed to install numpy without dependencies. Error: {}".format(e))
    print("Proceeding with regular installation...")

# Now try to install all dependencies, handling conflicts gracefully
print("\nStep 2: Installing all project dependencies...")
try:
    # Read requirements
    with open("requirements.txt", "r") as f:
        requirements = f.readlines()
        
    # Install each requirement with retries and special handling
    for req in requirements:
        req = req.strip()
        if req and not req.startswith('#'):
            print("Installing {}...".format(req))
            try:
                subprocess.check_call([sys.executable, "-m", "pip", "install", req] + user_flag)
            except subprocess.CalledProcessError as e:
                # If installation fails, try with --upgrade --force-reinstall
                print("  ⚠ Installation failed, retrying with --upgrade --force-reinstall...")
                try:
                    subprocess.check_call([sys.executable, "-m", "pip", "install", req, "--upgrade", "--force-reinstall"] + user_flag)
                except subprocess.CalledProcessError:
                    # If still fails, try ignoring dependencies
                    print("  ⚠ Still failing, trying with --no-deps...")
                    try:
                        subprocess.check_call([sys.executable, "-m", "pip", "install", req, "--no-deps"] + user_flag)
                    except subprocess.CalledProcessError:
                        print("  ❌ Failed to install {}. This might cause issues.".format(req))

    print("\n✓ Dependency installation process completed.")
    print("\nIf you encounter runtime errors, consider:")
    print("1. Creating a virtual environment to avoid system-wide package conflicts")
    print("2. Updating pip: python -m pip install --upgrade pip --user")
    print("3. Checking for specific package incompatibilities in error messages")

except Exception as e:
    print("\n❌ Error during dependency installation: {}".format(e))
    sys.exit(1)

# Test if key packages are importable
try:
    print("\nStep 3: Verifying key package installations...")
    import flask
    import moviepy.editor
    import numpy
    import imageio
    import waitress
    import proglog
    print("✓ All key packages are successfully importable!")
except ImportError as e:
    print("⚠ Warning: Some packages failed to import: {}".format(e))
    print("Please check the error messages above and try to resolve manually.")
    print("\nSuggestion: Try creating a virtual environment with:")
    print("python -m venv venv")
    print(".\\venv\\Scripts\\activate")
    print("pip install -r requirements.txt")